-- Pierwotny właściciel i twórca kodu: AmaMa
-- Zakaz używania / edycji kodu bez wcześniejszej zgody ze strony właściciela
-- Zakaz wykorzystywania całego lub fragmentów kodu
-- W przypadku złamania powyzszych zasad sprawa zostanie skierowana do sądu pod zarzutem: Naruszenia majątkowych praw autorskich
-- Pierwotnie pełne prawo do używania tego kodu posiada tylko AmaMa

vehicles=0
root=getRootElement()
resourceRoot=getResourceRootElement(getThisResource())

function getVehicleHandlingProperty ( element, property )
    if isElement ( element ) and getElementType ( element ) == "vehicle" and type ( property ) == "string" then
        local handlingTable = getVehicleHandling ( element )
        local value = handlingTable[property]
        if value then
            return value
        end
    end
    return false
end

local vehicleEngines = {
    ["1.0"] = {
        vehicleAcceleration = -1;
    };
    ["1.0T"] = {
        vehicleAcceleration = -0.2;
    };
    ["1.1"] = {
        vehicleAcceleration = -0.7;
    };
    ["1.1T"] = {
        vehicleAcceleration = 0.1;
    };
    ["1.2"] = {
        vehicleAcceleration = -0.8;
    };
    ["1.2T"] = {
        vehicleAcceleration = 0;
    };
    ["1.3"] = {
        vehicleAcceleration = -0.4;
    };
    ["1.3T"] = {
        vehicleAcceleration = 0.4;
    };
    ["1.4"] = {
        vehicleAcceleration = -0.6;
    };
    ["1.4T"] = {
        vehicleAcceleration = 0.2;
    };
    ["1.5"] = {
        vehicleAcceleration = -0.1;
    };
    ["1.5T"] = {
        vehicleAcceleration = 0.7;
    };
    ["1.6"] = {
        vehicleAcceleration = -0.4;
    };
    ["1.6T"] = {
        vehicleAcceleration = 0.4;
    };
    ["1.7"] = {
        vehicleAcceleration = 0.2;
    };
    ["1.7T"] = {
        vehicleAcceleration = 1;
    };
    ["1.8"] = {
        vehicleAcceleration = -0.2;
    };
    ["1.8T"] = {
        vehicleAcceleration = 0.6;
    };
    ["1.9"] = {
        vehicleAcceleration = 0.4;
    };
    ["1.9T"] = {
        vehicleAcceleration = 1.3;
    };
    ["2.0"] = {
        vehicleAcceleration = 0;
    };
    ["2.0T"] = {
        vehicleAcceleration = 0.8;
    };
    ["2.1"] = {
        vehicleAcceleration = 0.9;
    };
    ["2.1T"] = {
        vehicleAcceleration = 1.7;
    };
    ["2.2"] = {
        vehicleAcceleration = 0.3;
    };
    ["2.2T"] = {
        vehicleAcceleration = 1.1;
    };
    ["2.3"] = {
        vehicleAcceleration = 1.3;
    };
    ["2.3T"] = {
        vehicleAcceleration = 2.1;
    };
    ["2.4"] = {
        vehicleAcceleration = 0.6;
    };
    ["2.4T"] = {
        vehicleAcceleration = 1.4;
    };
    ["2.5"] = {
        vehicleAcceleration = 1.7;
    };
    ["2.5T"] = {
        vehicleAcceleration = 2.5;
    };
    ["2.6"] = {
        vehicleAcceleration = 0.9;
    };
    ["2.6T"] = {
        vehicleAcceleration = 1.7;
    };
    ["2.7"] = {
        vehicleAcceleration = 2.1;
    };
    ["2.7T"] = {
        vehicleAcceleration = 2.9;
    };
    ["2.8"] = {
        vehicleAcceleration = 1.2;
    };
    ["2.8T"] = {
        vehicleAcceleration = 2.0;
    };
    ["2.9"] = {
        vehicleAcceleration = 2.5;
    };
    ["2.9T"] = {
        vehicleAcceleration = 3.3;
    };
    ["3.0"] = {
        vehicleAcceleration = 1.6;
    };
    ["3.0T"] = {
        vehicleAcceleration = 2.4;
    };
    ["3.1"] = {
        vehicleAcceleration = 3.0;
    };
    ["3.1T"] = {
        vehicleAcceleration = 3.8;
    };
	["3.2"] = {
        vehicleAcceleration = 2.0;
    };
	["3.2T"] = {
        vehicleAcceleration = 2.8;
    };
	["3.3"] = {
        vehicleAcceleration = 3.5;
    };
	["3.3T"] = {
        vehicleAcceleration = 4.3;
    };
	["3.4"] = {
        vehicleAcceleration = 2.4;
    };
	["3.4T"] = {
        vehicleAcceleration = 3.2;
    };
	["3.5"] = {
        vehicleAcceleration = 4.0;
    };
	["3.5T"] = {
        vehicleAcceleration = 4.8;
    };
	["3.6"] = {
        vehicleAcceleration = 2.8;
    };
	["3.6T"] = {
        vehicleAcceleration = 3.6;
    };
	["3.7"] = {
        vehicleAcceleration = 4.5;
    };
	["3.7T"] = {
        vehicleAcceleration = 5.3;
    };
	["3.8"] = {
        vehicleAcceleration = 3.2;
    };
	["3.8T"] = {
        vehicleAcceleration = 4.0;
    };
	["3.9"] = {
        vehicleAcceleration = 5.0;
    };
	["3.9T"] = {
        vehicleAcceleration = 5.8;
    };
	["4.0"] = {
        vehicleAcceleration = 3.7;
    };
	["4.0T"] = {
        vehicleAcceleration = 4.5;
    };
	["4.1"] = {
        vehicleAcceleration = 5.6;
    };
	["4.1T"] = {
        vehicleAcceleration = 6.4;
    };
	["4.2"] = {
        vehicleAcceleration = 4.2;
    };
	["4.2T"] = {
        vehicleAcceleration = 5.0;
    };
	["4.3"] = {
        vehicleAcceleration = 6.2;
    };
	["4.3T"] = {
        vehicleAcceleration = 7.0;
    };
	["4.4"] = {
        vehicleAcceleration = 4.7;
    };
	["4.4T"] = {
        vehicleAcceleration = 5.5;
    };
	["4.5"] = {
        vehicleAcceleration = 6.8;
    };
	["4.5T"] = {
        vehicleAcceleration = 7.6;
    };
	["4.6"] = {
        vehicleAcceleration = 5.2;
    };
	["4.6T"] = {
        vehicleAcceleration = 6.0;
    };
	["4.7"] = {
        vehicleAcceleration = 7.4;
    };
	["4.7T"] = {
        vehicleAcceleration = 8.2;
    };
	["4.8"] = {
        vehicleAcceleration = 5.7;
    };
	["4.8T"] = {
        vehicleAcceleration = 6.5;
    };
	["4.9"] = {
        vehicleAcceleration = 8.0;
    };
	["4.9T"] = {
        vehicleAcceleration = 8.8;
    };
	["5.0"] = {
        vehicleAcceleration = 6.2;
    };
	["5.0T"] = {
        vehicleAcceleration = 7.0;
    };



}


function onRespawnVehicles(_,id,poss,win,plr)
	if id then
		result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_pojazdy WHERE parking=1 AND id=?", id)
		query=exports["cmta-db"]:dbSet("UPDATE cmta_pojazdy SET parking=0 WHERE id=?", id)
	else
		result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_pojazdy WHERE parking=0")
	end
	for ile,vehicle in pairs(result) do
		if vehicle["policeparking"] == 1 then return end
        vehicles=ile
		if id then pos={poss[1], poss[2], poss[3], poss[4], poss[5], poss[6]}
        else pos=split(vehicle["pos"], ",") end
		local color=split(vehicle["color"], ",")
        local lights=split(vehicle["headlights"], ",")
        local veh=createVehicle(vehicle["model"], pos[1], pos[2], pos[3], pos[4], pos[5], pos[6])
        setVehicleColor(veh, color[1], color[2], color[3], color[4],color[5], color[6], color[7], color[8],color[9], color[10], color[11], color[12])
        setVehicleHeadLightColor(veh, lights[1], lights[2], lights[3])
		if vehicle["plateText"] ~= "" then
		setVehiclePlateText(veh, vehicle["plateText"])
		else
		setVehiclePlateText(veh, tostring(""..vehicle["id"]))
		end
		setElementFrozen(veh, (vehicle["frozen"]) > 0)
	    setElementHealth(veh, vehicle["health"])
        setElementData(veh,"vehicle:spawn",true)
        setElementData(veh,"vehicle:id", vehicle["id"])
        setElementData(veh,"vehicle:fuel", vehicle["fuel"])
        setElementData(veh,"vehicle:mileage", vehicle["mileage"])
        setElementData(veh,"vehicle:driver", vehicle["driver"])		
        setElementData(veh,"vehicle:ownedGroup", vehicle["ownedGroup"])
        setElementData(veh,"vehicle:ownedPlayer", vehicle["ownedPlayer"])
		setElementData(veh,"vehicle:driveType", vehicle["driveType"])		
		setElementData(veh,"vehicle:engine", vehicle["engine"])		
		setElementData(veh,"vehicle:engineType", vehicle["engineType"])		
		setElementData(veh,"vehicle:tank", vehicle["tank"])	
		setElementData(veh,"vehicle:colorspeedo", vehicle["colorspeedo"])	
		setElementData(veh,"vehicle:launchcontrol", vehicle["LaunchControl"])	
		setElementData(veh,"vehicle:shader", vehicle["shader"])	
		setElementData(veh,"vehicle:mk1", vehicle["mk1"])	
		setElementData(veh,"vehicle:mk2", vehicle["mk2"])	
		setElementData(veh,"vehicle:mk3", vehicle["mk3"])	
		setElementData(veh,"vehicle:esp", vehicle["esp"])	

		setElementDimension(veh,tonumber(vehicle["dimension"]))		
        
		if getElementData(veh, "vehicle:driveType") == "AWD" then
		setVehicleHandling(veh, "driveType", "awd")
		elseif getElementData(veh, "vehicle:driveType") == "RWD" then
		setVehicleHandling(veh, "driveType", "rwd")
		elseif getElementData(veh, "vehicle:driveType") == "FWD" then
		setVehicleHandling(veh, "driveType", "fwd")
		end
		
		setVehicleHandling(veh,"engineAcceleration",getVehicleHandlingProperty(veh,"engineAcceleration") + vehicleEngines[vehicle["engine"]].vehicleAcceleration)

        if vehicle["spoiler"] ~= 0 then
        local spoiler=split(vehicle["spoilerOffsets"], ",")

        local spojler = createObject( vehicle["spoiler"], -1745.15491, -137.97495, 3.55469+0.60)
        attachElements ( spojler, veh, spoiler[1],spoiler[2],spoiler[3])
        setObjectScale(spojler,(spoiler[4] or 1))
        setElementData(veh, "vehicle:spoiler", spojler)

        end

		if vehicle["mk1"] == 1 then
			setVehicleHandling(veh,"engineAcceleration",getVehicleHandlingProperty(veh,"engineAcceleration")+0.8)
		end
		if vehicle["mk2"] == 1 then
			setVehicleHandling(veh,"engineAcceleration",getVehicleHandlingProperty(veh,"engineAcceleration") +1)
		end
		if vehicle["mk3"] == 1 then
			setVehicleHandling(veh,"engineAcceleration",getVehicleHandlingProperty(veh,"engineAcceleration") +1.3)
		end
		if (type(vehicle['rent']) == "string") then
		local tabelka = {}
		local rente = split(vehicle['rent'], ',')
		for k,v in ipairs(rente) do
		table.insert(tabelka,v)
		end
		setElementData(veh,"vehicle:rent", tabelka or false)
		else
		setElementData(veh,"vehicle:rent",0)
		end	
		for i,v in ipairs(split(vehicle["tuning"], ",")) do addVehicleUpgrade(veh, v) end
		
		for _, upgrade in ipairs ( getVehicleUpgrades ( veh ) ) do
			if upgrade == 1025 then
			setVehicleHandling(veh, "handlingFlags", 3145729)
			end
		end

		setVehicleDamageProof(veh, true)
		setElementFrozen(veh,false)
		if win == true then
		warpPedIntoVehicle(plr,veh)
		triggerClientEvent(plr,"pssm_vehicles:clear",plr,veh)
		end
	end
end

function getMyData ( thePlayer, command )
    local data = getAllElementData ( getPedOccupiedVehicle(thePlayer) )     -- get all the element data of the player who entered the command
    for k, v in pairs ( data ) do                    -- loop through the table that was returned
        outputConsole ( k .. ": " .. tostring ( v ) )             -- print the name (k) and value (v) of each element data, we need to make the value a string, since it can be of any data type
    end
end
addCommandHandler ( "elemdata", getMyData )

function onSaveVehicle(vehicle)
    if getElementData(vehicle,"vehicle:spawn") then
		local model=getElementModel(vehicle)
        local health=getElementHealth(vehicle)
        local x,y,z=getElementPosition(vehicle)
        local rx,ry,rz=getElementRotation(vehicle)
        local id=getElementData(vehicle,"vehicle:id")
        local fuel=getElementData(vehicle,"vehicle:fuel")
        local mileage=getElementData(vehicle,"vehicle:mileage")
        local c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12=getVehicleColor(vehicle, true)
        local driver=getElementData(vehicle,"vehicle:driver") or ""
		local driveType=getElementData(vehicle,"vehicle:driveType")
		local engine=getElementData(vehicle,"vehicle:engine")
		local engineType=getElementData(vehicle,"vehicle:engineType")
		local tank=getElementData(vehicle,"vehicle:tank")
        local player=getElementData(vehicle,"vehicle:ownedPlayer")
		local group=getElementData(vehicle,"vehicle:ownedGroup")
        local h1,h2,h3=getVehicleHeadLightColor(vehicle)
        local frozen= isElementFrozen(vehicle) and 1 or 0
        upgrades=getVehicleUpgrades(vehicle)
        if not upgrades then upgrades={} end
        upgrades=table.concat(upgrades, ",")
		local query = exports["cmta-db"]:dbSet(string.format("UPDATE cmta_pojazdy SET model='%d', pos='%.2f,%.2f,%.2f,%.2f,%.2f,%.2f', health='%d', fuel='%d', mileage='%d', frozen='%d', driver='%s', color='%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d', tuning='%s', headlights='%d,%d,%d', ownedPlayer='%d', driveType='%s', engine='%s', engineType='%s', tank='%d', dimension='%d' WHERE id=%d",
        model, x,y,z,rx,ry,rz, health, fuel, mileage, frozen, driver, c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12, upgrades, h1,h2,h3, player, driveType, engine, engineType, tank, getElementDimension(vehicle), id))
    else
	end
end

function onParkVehicle(vehicle) 
	local query=exports["cmta-db"]:dbSet("UPDATE cmta_pojazdy SET parking=1 WHERE id=?", getElementData(vehicle,"vehicle:id"))
	if query then
        destroyElement(vehicle)
	end
end



function getSettings(plr,code,value)
	local uid=getElementData(plr,"player:uid")
	if not uid then return end
	if value == "komis" then
		local result=exports["cmta-db"]:dbGet("SELECT * FROM pssm_dealers WHERE uid=?",uid)
		if result and #result > 0 then
			return result[1].code
		else
			return false
		end
	end
	if value == "owner" then
		local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_users WHERE id=?", uid)
		if result and #result > 0 then
			return result[1].id
		else
			return false
		end
	end
end

addEventHandler("onVehicleExit", root, function(plr,seat)
    if seat ~= 0 then return end
	if not source then return end
   	if getElementData(source,"vehicle:id") then
	onSaveVehicle(source)
	setVehicleDamageProof(source, true)
	end
end)

addEventHandler("onPlayerQuit", root, function()
    local veh=getPedOccupiedVehicle(source)
    if veh then
		setVehicleDamageProof(source, true)
    	onSaveVehicle(veh)
    end
end)

addEventHandler("onResourceStop", resourceRoot, function()
    for i,v in ipairs(getElementsByType("vehicle")) do
    	onSaveVehicle(v)
        if getElementData(v,"vehicle:spoiler") then
            destroyElement(getElementData(v,"vehicle:spoiler"))
        end
    end
end)

addEventHandler("onVehicleStartEnter", resourceRoot, function(plr,seat,jacked)
	if seat == 0 then
		if getElementHealth(source) <= 250 then setElementHealth(source,500) end
    	local rent=getElementData(source, "vehicle:rent")
    	local group1=getElementData(source, "vehicle:ownedGroup")
    	local player=getElementData(source, "vehicle:ownedPlayer")
		if rent and (type(rent) == "table") then
			for i,s in pairs(rent) do
				if tonumber(s) == getElementData(plr,"player:uid") then
				return end
			end
		end
		if player and player ~= getSettings(plr,false,"owner") then
			cancelEvent()
		end
    end
end)

addEventHandler("onResourceStart", resourceRoot, function() onRespawnVehicles(_,false) end)

addEventHandler("onVehicleEnter", resourceRoot, function(plr,seat,jacked)
    local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_bans WHERE time>NOW() AND type=? AND uid=? LIMIT 1","zabrane prawo jazdy",getElementData(plr,"player:uid"))
    if result and #result > 0 then
        setTimer(setControlState, 100, 1, plr,"enter_exit", true)
        setTimer(setControlState, 1000, 1, plr,"enter_exit", false)
        outputChatBox("#808080Posiadasz zawieszone prawo jazdy do #ccc000"..result[1]["time"].." #808080za #ccc000"..result[1]["reason"].."", plr, 255, 0, 0,true)
    else
        exports["cmta-db"]:dbSet("DELETE FROM cmta_bans WHERE type=? AND uid=?", "zabrane prawo jazdy", getElementData(plr,"player:uid"))
    end
end)

function shuffle(t)
  local n = #t
  while n >= 2 do
  local k = math.random(n)
  t[n], t[k] = t[k], t[n]
  n = n - 1
  end
  return t
end

local function vr()

	local pojazdy=getElementsByType("vehicle")
	if (#pojazdy<1) then return end

	local pojazdwoda={}
	for _,pojazd in ipairs(pojazdy) do
		onSaveVehicle(pojazd)
		if isElementInWater(pojazd) and not getVehicleController(pojazd) then
			local x,y,z=getElementPosition(pojazd)
			if (z<-1) then
				table.insert(pojazdwoda,pojazd)
			end
		end
	end
	if (#pojazdwoda<1) then return end


	shuffle(pojazdwoda)
	
	local pojazd=pojazdwoda[1]
	if getElementData(pojazd, "vehicle:spawn") then
		onParkVehicle(pojazd)
	else
		respawnVehicle(pojazd)
	end
end
setTimer(vr, 35000, 0)

local function pojazdPusty(veh)
	if not veh then return end
		local occupants = getVehicleOccupants(veh)
		local seats = getVehicleMaxPassengers(veh)
		if (not seats) then return true end
		for i=0,seats do
		local occupant = occupants[seat]
		if occupant and (getElementType(occupant)=="player" or getElementType(occupant)=="ped") and getPedOccupiedVehicleSeat(occupant) == i then
			return false
		end
		end
		return true
	end
	
	
	for i,v in ipairs(getElementsByType("vehicle")) do
		if (pojazdPusty(v)) then
			setVehicleDamageProof(v,true)
		else
		if getElementData(v,"damageproof") then setVehicleDamageProof(v, true) return end
		setVehicleDamageProof(v,false)
		end
	end
	
	addEventHandler ( "onVehicleEnter", root, function()
	if source then
		if getElementData(source,"damageproof") then setVehicleDamageProof(source, true) return end
		setVehicleDamageProof(source, false)
		end
	end)
	
	addEventHandler ( "onVehicleExit", root, function()
		if source then
		if (pojazdPusty(source)) then
			setVehicleDamageProof(source, true)
		else
			if getElementData(source,"damageproof") then setVehicleDamageProof(source, true) return end
			setVehicleDamageProof(source, false)
		end
		end
	end)

	function displayVehicleLoss(loss)
		local thePlayer = getVehicleOccupant(source)
		if(thePlayer) then
			if getElementHealth ( source ) < 300 then 
				setElementHealth ( source, 300 )
		  end 
		end
	end
	addEventHandler("onVehicleDamage", root, displayVehicleLoss)